package com.chagee.store.operation.server.event.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chagee.personnel.api.event.bo.PersonnelInfo;
import com.chagee.store.operation.api.enums.*;
import com.chagee.store.operation.api.response.TaskExecutionResponse;
import com.chagee.store.operation.api.response.vo.AiResultVO;
import com.chagee.store.operation.api.response.vo.FileVO;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.common.enums.LarkMessageTypeEnum;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.server.entity.*;
import com.chagee.store.operation.server.event.dao.*;
import com.chagee.store.operation.server.model.bo.OrderAppealRecordBO;
import com.chagee.store.operation.server.model.bo.StoreDetailBO;
import com.chagee.store.operation.server.model.info.LarkMessageInfo;
import com.chagee.store.operation.server.model.lock.TaskAppealsLock;
import com.chagee.store.operation.server.model.param.ApprovalAppealParam;
import com.chagee.store.operation.server.model.param.GetTaskRequest;
import com.chagee.store.operation.server.model.param.StoreAppSweepQueryParam;
import com.chagee.store.operation.server.model.param.SupplierDealWorkOrderParam;
import com.chagee.store.operation.server.model.param.ViewReasonsParam;
import com.chagee.store.operation.api.bo.AppealExtraVO;
import com.chagee.store.operation.server.model.vo.ApprovalAppealReasonResponse;
import com.chagee.store.operation.server.redis.service.RedisLockService;
import com.chagee.store.operation.server.service.biz.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

import com.chagee.store.operation.server.service.third.FeiShuSendService;
import com.chagee.storeManagement.api.event.request.OperateRecordRequest;
import com.google.common.collect.Sets;
import com.personnel.auth.service.PersonnelAuthService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class TaskExecutionBaseService extends ServiceImpl<TaskExecutionMapper, TaskExecutionDO> {

	@Resource
	private TaskExecutionMapper taskExecutionMapper;

	@Resource
	private WorkOrderMapper workOrderMapper;

	@Resource
	private WorkOrderReceiverMapper workOrderReceiverMapper;

	@Resource
	private FeiShuMessageBizService feiShuMessageBizService;

	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;

	@Resource
	private WorkOrderBaseService workOrderBaseService;

	@Resource
	private RedisLockService redisLockService;

	@Resource
	private FeiShuSendService feiShuSendService;

	@Resource
	private OperateRecordBizService operateRecordBizService;

	@Resource
	private StoreDetailMapper storeDetailMapper;

	@Resource
	private AppealReviewerConfigurationBaseService addAppealReviewerBaseService;

	@Resource
	private PersonnelAuthService personnelAuthService;


	private final SimpleDateFormat format = new SimpleDateFormat(CommonConstant.FORMAT);

	public Page<TaskExecutionDO> waitTaskList(StoreAppSweepQueryParam queryParameter, Page<TaskExecutionDO> page) {
		return baseMapper.waitTaskList(page, queryParameter);
	}
	public Page<TaskExecutionDO> queryList(StoreAppSweepQueryParam queryParameter, Page<TaskExecutionDO> page) {
		return baseMapper.selectPage(page, queryParameter);
	}

	/**
	 * 根据工单编号查询工单信息
	 *
	 * @param workOrderNumber 工单编号
	 * @return 工单信息
	 */
	public List<TaskExecutionDO> selectByWorkOrderNumber(String workOrderNumber) {
		return taskExecutionMapper.selectByWorkOrderNumber(workOrderNumber);
	}

	/**
	 * 根据工单编号查询工单信息
	 *
	 * @param supplierDealWorkOrderParam 工单编号
	 * @return 工单信息
	 */
	public List<TaskExecutionDO> dealWorkOrder(SupplierDealWorkOrderParam supplierDealWorkOrderParam) {
		return taskExecutionMapper.selectByWorkOrderNumber(supplierDealWorkOrderParam.getWorkOrderNumber());
	}

	/**
	 * 获取该门店下该任务昨日的验收结果（满意/不满意/无此项）
	 *
	 * @param getTaskRequest 入参
	 * @return 结果
	 */
	public List<TaskExecutionDO> getTaskExecutionEarlyAcceptance(GetTaskRequest getTaskRequest) {
		return taskExecutionMapper.getTaskExecutionEarlyAcceptance(getTaskRequest);
	}

	/**
	 * 查询工单下的任务信息（任务的申诉状态不为空的）
	 *
	 * @param workOrderNumber 工单编号
	 * @return 任务信息（任务的申诉状态不为空的）
	 */
	public List<TaskExecutionResponse> queryTaskExecutionList(String workOrderNumber, String storeNo) {
		PersonnelInfo loginUser = personnelAuthService.getLoginUserInfoInWeb();
		log.info("TaskExecutionBaseService.queryTaskExecutionList.loginUser {}", JSONUtil.toJsonStr(loginUser));
		List<TaskExecutionResponse> taskExecutionResponseList = new ArrayList<>();
		if (StringUtils.isBlank(workOrderNumber)) {
			throw new BizException(BizErrorCode.PARAMETER_IS_NULL);
		}
		//查询工单关联的任务信息
		LambdaQueryWrapper<TaskExecutionDO> taskExecutionDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
		taskExecutionDOLambdaQueryWrapper
			.eq(TaskExecutionDO::getWorkOrderNumber, workOrderNumber)
			.isNotNull(TaskExecutionDO::getAppealStatus)
			.eq(TaskExecutionDO::getDeleteFlag, NumberUtils.INTEGER_ZERO)
			.orderByAsc(TaskExecutionDO::getAppealStatus);
		List<TaskExecutionDO> taskExecutionDOList = taskExecutionMapper.selectList(taskExecutionDOLambdaQueryWrapper);
		if (CollectionUtils.isNotEmpty(taskExecutionDOList)) {
			List<StoreDetailBO> storeDetailBOS = storeDetailMapper.selectListByStoreNos(CollectionUtil.newArrayList(storeNo));
			StoreDetailBO storeDetailBO = storeDetailBOS.stream().findFirst().orElseThrow(() -> new BizException(BizErrorCode.NOT_GTE_STORE_INFO));

			//市编码
			String code = storeDetailBO.getRegion().split(CommonConstant.OR_STRING)[1];

			//当前登录人配置的管辖城市
			Set<Integer> regions = Sets.newHashSet();
			if (Objects.nonNull(loginUser.getId())) {
				List<AppealReviewerConfigurationDO> appealReviewerDOS = addAppealReviewerBaseService.queryByReveiwerId(String.valueOf(loginUser.getId()));
				if (CollectionUtil.isNotEmpty(appealReviewerDOS)) {
					List<String> regionList = appealReviewerDOS.stream().map(AppealReviewerConfigurationDO::getCityRegion).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
					regions = getRegion(regionList);
				}
			}
			Boolean handleAppealButton = Boolean.FALSE;
			if (regions.contains(Integer.parseInt(code))) {
				handleAppealButton = true;
			}

			List<AppealReviewerConfigurationDO> configurationDOS = addAppealReviewerBaseService.queryByRegion(code);
			//该工单所属门店未配置申诉审核人; 均可操作处理申诉按钮
			if (CollectionUtil.isEmpty(configurationDOS)) {
				handleAppealButton = true;
			}
			Boolean finalHandleAppealButton = handleAppealButton;

			taskExecutionDOList.forEach(taskExecutionDO -> {
				TaskExecutionResponse taskExecutionResponse = new TaskExecutionResponse();
				BeanUtils.copyProperties(taskExecutionDO, taskExecutionResponse);
				//示意图
				if (StringUtils.isNotBlank(taskExecutionDO.getSchematicDrawing())) {
					taskExecutionResponse.setSchematicDrawing(JSON.parseArray(taskExecutionDO.getSchematicDrawing(), FileVO.class));
				}
				//拍照图片
				if (StringUtils.isNotBlank(taskExecutionDO.getTakePictures())) {
					taskExecutionResponse.setTakePictures(JSON.parseArray(taskExecutionDO.getTakePictures(), AiResultVO.class));
				}
				//备注图片附件
				if (StringUtils.isNotBlank(taskExecutionDO.getRemarkPicture())) {
					taskExecutionResponse.setRemarkPicture(JSON.parseArray(taskExecutionDO.getRemarkPicture(), FileVO.class));
				}
				//打烊验收
				if (Objects.nonNull(taskExecutionDO.getClosingInspection())) {
					taskExecutionResponse.setClosingInspectionValue(Objects.requireNonNull(ClosingInspectionEnum.queryByType(taskExecutionDO.getClosingInspection())).getDesc());
				}
				//开早验收
				if (StringUtils.isNotBlank(taskExecutionDO.getEarlyAcceptance())) {
					taskExecutionResponse.setEarlyAcceptanceValue(Objects.requireNonNull(StoreTaskEnum.queryByType(taskExecutionDO.getEarlyAcceptance())).getDesc());
				}
				//申诉状态
				if (Objects.nonNull(taskExecutionDO.getAppealStatus())) {
					taskExecutionResponse.setAppealStatusValue(Objects.requireNonNull(AppealStatusEnum.getByType(taskExecutionDO.getAppealStatus())).getDesc());
				}
				if (StringUtils.isNotBlank(taskExecutionDO.getExtra())) {
					AppealExtraVO appealExtraVO = JSON.parseObject(taskExecutionDO.getExtra(), AppealExtraVO.class);
					taskExecutionResponse.setExtraVO(appealExtraVO);
				}
				taskExecutionResponse.setHandleAppealButton(finalHandleAppealButton);
				taskExecutionResponseList.add(taskExecutionResponse);
			});
		}
		return taskExecutionResponseList;
	}

	//获取市
	public Set<Integer> getRegion(List<String> cityList) {
		Set<Integer> cityRegionList = Sets.newHashSet();

		Set<String> strings = Sets.newHashSet();
		cityList.forEach(s -> {
			//["123,4324","123,4324"]
			List<String> lists = JSONObject.parseArray(s, String.class);
			strings.addAll(lists);
		});
		if (CollectionUtil.isNotEmpty(strings)) {
			for (String code : strings) {
				if (StringUtils.isNotBlank(code)) {
					String[] regionCode = code.split(CommonConstant.OR_STRING);
					if (regionCode.length > 0) {
						cityRegionList.add(Integer.parseInt(regionCode[1]));
					}
				}
			}
		}
		return cityRegionList;
	}

	/**
	 * PC端开早打样工单-申诉信息：审批申诉（通过/驳回）
	 *
	 * @param approvalAppealParam 审批入参
	 * @return true/false
	 */
	public Boolean approvalAppeals(ApprovalAppealParam approvalAppealParam) {
		BladeUser user = AuthUtil.getUser();
		Long userId = user.getUserId();
		String userName = user.getNickName();
		if (Objects.isNull(approvalAppealParam) || Objects.isNull(approvalAppealParam.getTaskExecutionId())
			|| StringUtils.isBlank(approvalAppealParam.getApprovalFlag())) {
			throw new BizException(BizErrorCode.PARAMETER_IS_NULL);
		}
		//1先查询
		LambdaQueryWrapper<TaskExecutionDO> taskExecutionDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
		taskExecutionDOLambdaQueryWrapper
			.eq(TaskExecutionDO::getId, approvalAppealParam.getTaskExecutionId())
			.eq(TaskExecutionDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		TaskExecutionDO taskExecutionDO = taskExecutionMapper.selectOne(taskExecutionDOLambdaQueryWrapper);
		if (Objects.isNull(taskExecutionDO)) {
			throw new BizException(BizErrorCode.NO_TASK_EXECUTION_DATA);
		}
		//2再赋值修改
		//审批通过
		if (CommonConstant.APPROVAL_FLAG_Y.equals(approvalAppealParam.getApprovalFlag())) {
			taskExecutionDO.setAppealStatus(AppealStatusEnum.PASSED.getType());
			//同时修改 验收结果 的状态为 合格 StoreTaskEnum.YES
			taskExecutionDO.setEarlyAcceptance(StoreTaskEnum.YES.getType());
		}
		//审批驳回
		if (CommonConstant.APPROVAL_FLAG_N.equals(approvalAppealParam.getApprovalFlag())) {
			taskExecutionDO.setAppealStatus(AppealStatusEnum.REJECTED.getType());
			//将驳回原因和证明入拓展字段
//			AppealExtraVO appealExtraVO = JSON.parseObject(taskExecutionDO.getExtra(), AppealExtraVO.class);
//			if (StringUtils.isNotBlank(approvalAppealParam.getRejectReason())) {
//				appealExtraVO.setRejectReason(approvalAppealParam.getRejectReason());
//			}
//			if (CollectionUtils.isNotEmpty(approvalAppealParam.getRejectCertificate())) {
//				appealExtraVO.setRejectCertificate(approvalAppealParam.getRejectCertificate());
//			}
//			taskExecutionDO.setExtra(JSONObject.toJSONString(appealExtraVO));
		}

		AppealExtraVO appealExtraVO = new AppealExtraVO();
		if (StringUtils.isNotBlank(taskExecutionDO.getExtra())) {
			appealExtraVO = JSON.parseObject(taskExecutionDO.getExtra(), AppealExtraVO.class);
		}
		appealExtraVO.setHandleAppealReason(approvalAppealParam.getHandleAppealReason());
		taskExecutionDO.setExtra(JSONObject.toJSONString(appealExtraVO));
		taskExecutionDO.setUpdateTime(new Date());
		taskExecutionMapper.updateById(taskExecutionDO);

		TaskAppealsLock lock = null;
		if (Objects.nonNull(taskExecutionDO.getWorkOrderNumber())) {
			lock = new TaskAppealsLock(taskExecutionDO.getWorkOrderNumber());
		}
		try {
			redisLockService.lockElseThrowError(lock, BizErrorCode.LOCK_EXCEPTION.getErrorMsg());
			//处理工单和工单接单人表的状态，
			updateWorkOrderStatus(taskExecutionDO.getWorkOrderNumber());
		} finally {
			redisLockService.unLock(lock);
		}
		log.info("供应商对工单{}的任务{}的验收结果不合格的申诉。", taskExecutionDO.getWorkOrderNumber(), taskExecutionDO.getTaskName());
		//审批通过时发送消息通知
		//if (CommonConstant.APPROVAL_FLAG_Y.equals(approvalAppealParam.getApprovalFlag())) {
		WorkOrderDO workOrderDO = workOrderBaseService.selectWorkOrder(taskExecutionDO.getWorkOrderNumber());
		feiShuSendService.sendTaskApprovalFeiShuMessage(workOrderDO, taskExecutionDO);
//				Boolean info1 = sendFeiShuMessage(taskExecutionDO);
//				if (!info1) {
//					return info1;
//				}
		//}

		// 操作日志
		OperateRecordRequest operateRecordRequest = new OperateRecordRequest();
		operateRecordRequest.setStoreNo(taskExecutionDO.getWorkOrderNumber());

		OrderAppealRecordBO updateBefore = new OrderAppealRecordBO();
		updateBefore.setDocumentStatus(StoreWorkOrderStatusEnum.IN_APPEAL.getDesc());
		operateRecordRequest.setUpdateBefore(JSON.toJSONString(updateBefore));

		OrderAppealRecordBO updateData = new OrderAppealRecordBO();
		updateData.setRecordName(RecordTypeEnum.APPROVAL_TASK_APPEAL.getDesc());
		updateData.setStoreTaskRelationId(approvalAppealParam.getTaskExecutionId());
		updateData.setTaskName(taskExecutionDO.getTaskName());
		updateData.setApproveAppealReason(approvalAppealParam.getHandleAppealReason());
		updateData.setAppealStatus(AppealStatusEnum.getByType(taskExecutionDO.getAppealStatus()).getDesc());
		operateRecordRequest.setUpdateData(JSON.toJSONString(updateData));

		operateRecordRequest.setUpdateFrom(StrUtil.isNotBlank(userName) ? userName : CommonConstant.OPERATE_SOURCE);
		operateRecordRequest.setUpdateFromCode(String.valueOf(userId));
		operateRecordBizService.updateOptRecord(operateRecordRequest);

		return true;
	}

	/**
	 * 审批通过时发送消息通知
	 *
	 * @param taskExecutionDO 工单关联任务信息
	 * @return true/false
	 */
	@NotNull
	private Boolean sendFeiShuMessage(TaskExecutionDO taskExecutionDO) {
		LambdaQueryWrapper<WorkOrderDO> workOrderDOWrapper = new LambdaQueryWrapper<>();
		workOrderDOWrapper
			.eq(WorkOrderDO::getWorkOrderNumber, taskExecutionDO.getWorkOrderNumber())
			.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		WorkOrderDO workOrderDO = workOrderMapper.selectOne(workOrderDOWrapper);
		if (Objects.isNull(workOrderDO)) {
			throw new BizException(BizErrorCode.NO_WORK_ORDER_DATA);
		}
		//发送消息
		LarkMessageInfo info = new LarkMessageInfo();
		info.setStoreNo(workOrderDO.getStoreCode());
		info.setWorkOrderNumber(taskExecutionDO.getWorkOrderNumber());
		info.setOrderCreateTime(format.format(workOrderDO.getCreateTime()));
		info.setTaskName(taskExecutionDO.getTaskName());
		info.setType(LarkMessageTypeEnum.appealSuccessNotice.getType());
		try {
			return feiShuMessageBizService.sendMessage(info);
		} catch (Exception e) {
			log.error("打烊工单{}发送飞书通知失败:", taskExecutionDO.getWorkOrderNumber(), e);
		}
		return false;
	}

	/**
	 * 每次审批申诉时都要去查询是否是最后一条待处理的，如果是则需要将工单和工单接单人的状态改为 已完成
	 *
	 * @param workOrderNumber 工单编码
	 */
	private void updateWorkOrderStatus(String workOrderNumber) {
		//查询该工单下面任务的申诉状态是否还存在待处理的，如无则将工单状态置为 已完成。
		LambdaQueryWrapper<TaskExecutionDO> taskExecutionDOLambdaQueryWrapperList = new LambdaQueryWrapper<>();
		taskExecutionDOLambdaQueryWrapperList
			.eq(TaskExecutionDO::getWorkOrderNumber, workOrderNumber)
			.eq(TaskExecutionDO::getAppealStatus, AppealStatusEnum.PENDING_PROCESSING.getType())
			.eq(TaskExecutionDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		List<TaskExecutionDO> taskExecutionDOList = taskExecutionMapper.selectList(taskExecutionDOLambdaQueryWrapperList);
		LambdaQueryWrapper<WorkOrderDO> workOrderDOWrapper = new LambdaQueryWrapper<>();
		WorkOrderDO workOrderDO = workOrderMapper.selectOne(
			workOrderDOWrapper.eq(WorkOrderDO::getWorkOrderNumber, workOrderNumber)
				.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO));
		//重新计算合格率
		calculateQualificationRate(workOrderDO);
		workOrderDO.setUpdateTime(new Date());

		Integer documentStatus = null;
		List<WorkOrderReceiverDO> workOrderReceiverDOList = workOrderReceiverBaseService.queryOrderByWorkOrderNumber(workOrderNumber);
		if (CollectionUtils.isEmpty(taskExecutionDOList)) {
			//修改工单和工单接单人表的状态为已完成
			if (Objects.nonNull(workOrderDO)) {
				workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.COMPLETED.getType());
			}
			documentStatus = StoreWorkOrderStatusEnum.COMPLETED.getType();
//				workOrderReceiverDOList.forEach(s -> {
//					s.setDocumentStatus(StoreWorkOrderStatusEnum.COMPLETED.getType());
//					s.setUpdateTime(new Date());
//					workOrderReceiverMapper.updateById(s);
//				});
		}
		if (CollectionUtils.isNotEmpty(workOrderReceiverDOList)) {
			workOrderReceiverBaseService.batchUpdateOrderStatus(workOrderReceiverDOList, documentStatus, workOrderDO.getDocumentScore());
		}
		workOrderMapper.updateById(workOrderDO);
	}

	/**
	 * 计算合格率
	 *
	 * @param workOrderDO 工单信息
	 */
	public void calculateQualificationRate(WorkOrderDO workOrderDO) {
		QueryWrapper<TaskExecutionDO> query = Wrappers.query();
		query.eq("work_order_number", workOrderDO.getWorkOrderNumber());
		List<TaskExecutionDO> taskExecutionDOS = taskExecutionMapper.selectList(query);
		if (CollectionUtils.isNotEmpty(taskExecutionDOS)) {
			List<TaskExecutionDO> yesOrders = taskExecutionDOS.stream().filter(s -> StringUtils.equals(StoreTaskEnum.YES.getType(), s.getEarlyAcceptance())
				|| StringUtils.equals(StoreTaskEnum.SYSTEM_SATISFIED.getType(), s.getEarlyAcceptance())).collect(Collectors.toList());
			List<TaskExecutionDO> emptyOrders = taskExecutionDOS.stream().filter(s -> StringUtils.equals(StoreTaskEnum.EMPTY.getType(), s.getEarlyAcceptance())).collect(Collectors.toList());
			if (StringUtils.isNotBlank(workOrderDO.getContinuousAcceptance()) && (StringUtils.equals(OrderTaskAcceptanceEnum.NO_PASS.getType(), workOrderDO.getContinuousAcceptance()) ||  StringUtils.equals(OrderTaskAcceptanceEnum.APPEAL_REJECTED.getType(), workOrderDO.getContinuousAcceptance()))) {
				workOrderDO.setDocumentScore(CommonConstant.ZERO);
			} else if (!CollectionUtils.isEmpty(yesOrders)) {
				// 工单评分  满意数量 / (总数量- 验收无此项) * 100
				BigDecimal score = new BigDecimal(yesOrders.size() * 100).divide(new BigDecimal(taskExecutionDOS.size() - emptyOrders.size()), NumberUtils.INTEGER_ZERO, BigDecimal.ROUND_HALF_UP);
				workOrderDO.setDocumentScore(score.toString());
			} else {
				workOrderDO.setDocumentScore(CommonConstant.ZERO);
			}
		}
	}

	/**
	 * PC端开早打样工单-申诉信息：查看驳回的原因/申诉原因
	 *
	 * @param viewReasonsParam 审批入参
	 * @return 申诉（驳回）原因证明
	 */
	public ApprovalAppealReasonResponse viewReasons(ViewReasonsParam viewReasonsParam) {
		if (Objects.isNull(viewReasonsParam) || Objects.isNull(viewReasonsParam.getTaskExecutionId())
			|| StringUtils.isBlank(viewReasonsParam.getApprovalFlag())) {
			throw new BizException(BizErrorCode.PARAMETER_IS_NULL);
		}
		LambdaQueryWrapper<TaskExecutionDO> taskExecutionDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
		taskExecutionDOLambdaQueryWrapper
			.eq(TaskExecutionDO::getId, viewReasonsParam.getTaskExecutionId())
			.eq(TaskExecutionDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		TaskExecutionDO taskExecutionDO = taskExecutionMapper.selectOne(taskExecutionDOLambdaQueryWrapper);
		if (Objects.isNull(taskExecutionDO)) {
			throw new BizException(BizErrorCode.NO_TASK_EXECUTION_DATA);
		}
		ApprovalAppealReasonResponse approvalAppealReasonResponse = new ApprovalAppealReasonResponse();
		BeanUtils.copyProperties(taskExecutionDO, approvalAppealReasonResponse);
		approvalAppealReasonResponse.setTaskExecutionId(taskExecutionDO.getId());
		if (Objects.nonNull(taskExecutionDO.getAppealStatus())) {
			approvalAppealReasonResponse.setAppealStatusValue(Objects.requireNonNull(AppealStatusEnum.getByType(taskExecutionDO.getAppealStatus())).getDesc());
		}
		String extra = taskExecutionDO.getExtra();
		if (StringUtils.isBlank(extra)) {
			//表示什么原因都没查到
			return approvalAppealReasonResponse;
		}
		AppealExtraVO appealExtraVO = JSON.parseObject(extra, AppealExtraVO.class);
		if (Objects.isNull(appealExtraVO)) {
			throw new BizException(BizErrorCode.EXTRA_CONVERT_EXCEPTION);
		}
		//查看申诉原因
		if (CommonConstant.APPROVAL_FLAG_Y.equals(viewReasonsParam.getApprovalFlag())) {
			approvalAppealReasonResponse.setReason(appealExtraVO.getAppealReason());
			approvalAppealReasonResponse.setCertificate(appealExtraVO.getAppealCertificate());
		}
		//查看审批不通过原因(功夫小程序验收不合格时的信息)
		if (CommonConstant.APPROVAL_FLAG_N.equals(viewReasonsParam.getApprovalFlag())) {
//			approvalAppealReasonResponse.setReason(appealExtraVO.getRejectReason());
//			approvalAppealReasonResponse.setCertificate(appealExtraVO.getRejectCertificate());
			if (StringUtils.isNotBlank(taskExecutionDO.getRemark())) {
				approvalAppealReasonResponse.setReason(taskExecutionDO.getRemark());
			}
			if (StringUtils.isNotBlank(taskExecutionDO.getRemarkPicture())) {
				approvalAppealReasonResponse.setCertificate(JSONArray.parseArray(taskExecutionDO.getRemarkPicture(), FileVO.class));
			}
			approvalAppealReasonResponse.setApprovalFlag(viewReasonsParam.getApprovalFlag());
		}
		return approvalAppealReasonResponse;
	}

	/**
	 * 更新
	 *
	 * @param taskExecutionDO taskExecutionDO
	 */
	public void update(TaskExecutionDO taskExecutionDO) {
		taskExecutionMapper.updateById(taskExecutionDO);
	}
	public void updateTaskExecution(TaskExecutionDO taskExecutionDO) {
		this.update(
			lambdaUpdate().eq(TaskExecutionDO::getId, taskExecutionDO.getId())
				.set(ObjectUtil.isNotEmpty(taskExecutionDO.getNoSuchItemFlag()), TaskExecutionDO::getNoSuchItemFlag, taskExecutionDO.getNoSuchItemFlag())
				.set(TaskExecutionDO::getTakePictures, StringUtils.isBlank(taskExecutionDO.getTakePictures()) ? "" : taskExecutionDO.getTakePictures())
				.set(ObjectUtil.isNotEmpty(taskExecutionDO.getClosingInspection()), TaskExecutionDO::getClosingInspection, taskExecutionDO.getClosingInspection())
				.set(TaskExecutionDO::getAiResult, Objects.isNull(taskExecutionDO.getAiResult()) ? null : taskExecutionDO.getAiResult())
				.set(StringUtils.isNotEmpty(taskExecutionDO.getSubmitter()), TaskExecutionDO::getSubmitter, taskExecutionDO.getSubmitter())
				.set(TaskExecutionDO::getCompletionTime, taskExecutionDO.getCompletionTime())
				.set(TaskExecutionDO::getDealStatus, taskExecutionDO.getDealStatus())
				.getWrapper());
	}

	public List<TaskExecutionDO> queryTaskList(List<String> orderNoList) {
		LambdaQueryWrapper<TaskExecutionDO> wrapper = new LambdaQueryWrapper();
		wrapper.eq(TaskExecutionDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		wrapper.in(TaskExecutionDO::getWorkOrderNumber, orderNoList);
		return this.list(wrapper);
	}

	public List<TaskExecutionDO> queryTaskByWorkOrderNumber(String workOrderNumber, Integer appealStatus) {
		LambdaQueryWrapper<TaskExecutionDO> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(TaskExecutionDO::getWorkOrderNumber, workOrderNumber)
			.eq(TaskExecutionDO::getAppealStatus, appealStatus)
			.eq(TaskExecutionDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		return taskExecutionMapper.selectList(wrapper);
	}

	public Boolean updateTaskAppealStatus(TaskExecutionDO taskExecutionDO, Integer appealStatus) {
		return this.update(
			lambdaUpdate().eq(TaskExecutionDO::getId, taskExecutionDO.getId())
				.set(ObjectUtil.isNotEmpty(appealStatus), TaskExecutionDO::getAppealStatus, appealStatus)
				.set(StringUtils.isNotEmpty(taskExecutionDO.getExtra()), TaskExecutionDO::getExtra, taskExecutionDO.getExtra())
				.set(TaskExecutionDO::getUpdateTime, new Date())
				.getWrapper());
	}

}
